import React, { Component } from 'react';
import { connect } from 'dva';
import {
    Spin,
    Button,
    message,
    Card,
    Table,
    Row,
    Col,
    Tooltip,
    Form,
    Input,
    Popconfirm,
    Cascader,
    Select,
    Drawer
} from 'antd';
import {PageHeaderWrapper} from "@ant-design/pro-layout";
import { FormattedMessage } from 'umi/locale';
import APP from "@/components/Tool/BaseAPP";
import moment from "moment";
import router from 'umi/router';
import ChinaArea from "@/components/Tool/ChinaArea";

/**
 * 分页参数
 * @Author 肖家添
 * @Date 2019/8/22 15:09
 */
let pagingData = {
    _pageSize: 10,
    _current: 1,
    _total: 0,
};

@connect(({ pointModel }) => ({
    pointModel
}))
@Form.create()
class point extends Component {
    state = {
        loading: false,
        pageDataSource: [],
        selectedKeys: [],
        isShowJournalListDrawer:false,
        journalList: [],
        selectedRows: []
    };

    componentDidMount() {
        this.findPageDataSource();
    }

    findPageDataSource = (e) => {
        let that = this, params = {...pagingData};
        if(e){
            pagingData._current = 1;
            e.preventDefault();
        }
        const { form } = this.props;
        form.validateFieldsAndScroll((err, values) => {
            APP.validNilParams(values);
            params = {...params, ...values};
            const area = params.area;
            if(area){
                delete params.area;
                if(area.length >= 1){
                    params.houseProvinceId = area[0];
                }
                if(area.length >= 2){
                    params.houseCityId = area[1];
                }
                if(area.length >= 3){
                    params.houseAreaId = area[2];
                }
            }
            requestContinue();
        });
        function requestContinue(){
            const { dispatch } = that.props;
            APP.loading(that);
            dispatch({
                type: "pointModel/list",
                payload: params,
                callback: function(data){
                    APP.closeLoading(that);
                    if(data.success){
                        const { list, pagination } = data.datas;
                        pagingData._current = pagination.current;
                        pagingData._pageSize = pagination.pageSize;
                        pagingData._total = pagination.total;
                        that.setState({
                            pageDataSource: list,
                            selectedKeys: [],
                            selectedRows: []
                        });
                    }
                }
            });
        }
    };

    getDataById = () => {
        const { selectedKeys } = this.state;
        if(selectedKeys.length !== 1) return;
        const that = this,
            { dispatch } = that.props,
            id = selectedKeys[0];
        router.push({
            pathname: '/point/editPoint',
            state: {id: id}
        });
    };

    enabledControl = (isEnabled) => {
        const { selectedKeys, selectedRows } = this.state;
        if(selectedKeys <= 0) return;
        const that = this, { dispatch } = this.props;
        const ids = selectedKeys.join(",");
        if (isEnabled !== 1) {
            for (let i = 0; i < selectedRows.length; i++) {
                const row = selectedRows[i];
                if (row.enaJournalCount > 0) {
                    message.error('机器串码“' + row.imei + '”的点位还有期刊关联，请先下架或删除期刊后再执行');
                    return;
                }
            }
        }
        APP.loading(that);
        dispatch({
            type: "pointModel/enabledControl",
            payload: {
                ids: ids,
                isEnabled: isEnabled
            },
            callback: function(data){
                APP.closeLoading(that);
                if(data.success){
                    message.success("操作成功");
                    that.findPageDataSource();
                }else{
                    message.error("操作失败！");
                }
            }
        });
    };

    exportData = (type) => {
        APP.exportData({
            parent: this,
            requestUrl: "/api/point/exportData",
            fileNamePrefix: "点位",
            exportType: type,
            tablePagination: pagingData
        });
    };

    onClose = () => {
        this.setState({
            isShowJournalListDrawer: false,
        });
    };

    render() {
        const {
            loading,
            pageDataSource,
            selectedKeys,
            isShowJournalListDrawer,
            journalList
        } = this.state;
        const { form } = this.props;
        const that = this;
        const { getFieldDecorator } = form;
        /**
         * 按钮样式
         * @Author 肖家添
         * @Date 2019/8/19 19:42
         */
        const buttonsStyle = {
            style: {
                marginRight: '15px',
            },
        };
        return (
            <Spin spinning={loading}>
                <PageHeaderWrapper title={<FormattedMessage id="menu.point.point"/>}>
                    <Card style={{marginBottom: 15}}>
                        <Form layout="inline" onSubmit={this.findPageDataSource}>
                            <Row>
                                <Col span={8}>
                                    <Form.Item label="楼盘名称">
                                        {getFieldDecorator('houseName', {})(<Input placeholder="请输入楼盘名称"/>)}
                                    </Form.Item>
                                </Col>
                                <Col span={8}>
                                    <Form.Item label="所属区域">
                                        {getFieldDecorator('area', {})(<Cascader placeholder={"清选择所属区域"} options={ChinaArea} />)}
                                    </Form.Item>
                                </Col>
                                <Col span={8}>
                                    <Form.Item label="点位名称">
                                        {getFieldDecorator('elevatorName', {})(<Input placeholder="请输入点位名称"/>)}
                                    </Form.Item>
                                </Col>
                                <Col span={8}>
                                    <Form.Item label="点位状态">
                                        {getFieldDecorator('xstatus', {})(
                                            <Select placeholder={"请选择状态"} allowClear={true} style={{width: 174}}>
                                                <Select.Option value={1}>正常</Select.Option>
                                                <Select.Option value={2}>离线</Select.Option>
                                                <Select.Option value={3}>损坏</Select.Option>
                                                <Select.Option value={4}>其他</Select.Option>
                                            </Select>
                                        )}
                                    </Form.Item>
                                </Col>
                                <Col span={8}>
                                    <Form.Item label="机器串码">
                                        {getFieldDecorator('imei', {})(<Input placeholder="请输入机器串码"/>)}
                                    </Form.Item>
                                </Col>
                            </Row>
                            <Row>
                                <Col style={{ textAlign: 'center', height: '32px', lineHeight: '32px', marginTop: 20 }}>
                                    <Button type="primary" htmlType="submit" {...APP.buttonsStyle_MR15}>
                                        查找
                                    </Button>
                                    <Button type="primary" {...APP.buttonsStyle_MR15} onClick={() => this.exportData(1)}>
                                        导出本页
                                    </Button>
                                    <Button type="primary" {...APP.buttonsStyle_MR15} onClick={() => this.exportData(2)}>
                                        导出所有
                                    </Button>
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <Card style={{marginBottom: 15}}>
                        <Button type="primary" {...buttonsStyle} onClick={() => {
                            router.push({
                                pathname: '/point/editPoint',
                                state: { }
                            });
                        }}>
                            新增
                        </Button>
                        <Tooltip title={selectedKeys.length === 1 ? '' : '请选中一行数据'}>
                            <Button type="primary" {...buttonsStyle} onClick={() => this.getDataById()}>
                                编辑
                            </Button>
                        </Tooltip>
                        <Tooltip title={selectedKeys.length > 0 ? '' : '请选中数据'}>
                            <Button type="primary" {...buttonsStyle} onClick={() => this.enabledControl(1)}>
                                上架
                            </Button>
                        </Tooltip>
                        <Tooltip title={selectedKeys.length > 0 ? '' : '请选中数据'}>
                            <Button type="primary" {...buttonsStyle} onClick={() => this.enabledControl(0)}>
                                下架
                            </Button>
                        </Tooltip>
                        <Tooltip title={selectedKeys.length > 0 ? '' : '请选中数据'}>
                            <Popconfirm
                                title="确定删除选中数据吗？"
                                onConfirm={() => this.enabledControl(-1)}
                                okText="删除"
                                cancelText="取消"
                                disabled={!(selectedKeys.length > 0)}
                            >
                                <Button type="primary" {...buttonsStyle}>
                                    删除
                                </Button>
                            </Popconfirm>
                        </Tooltip>
                    </Card>
                    <Card>
                        <Table
                            bordered
                            rowKey={data => `${data.id}`}
                            rowSelection={APP.tableRowSelection(function(selectedRowKeys, selectedRows){
                                that.setState({ selectedKeys: selectedRowKeys, selectedRows: selectedRows });
                            }, selectedKeys)}
                            columns={this.columns}
                            dataSource={pageDataSource}
                            pagination={{
                                pageSize: pagingData._pageSize,
                                current: pagingData._current,
                                total: pagingData._total,
                                onChange: (page, pageSize) => {
                                    pagingData._current = page;
                                    this.findPageDataSource();
                                },
                                showTotal: total => `共 ${total} 条数据`,
                            }}
                        />
                    </Card>
                    <Drawer
                        placement="right"
                        closable={false}
                        onClose={this.onClose}
                        visible={isShowJournalListDrawer}
                        width={500}
                        key="right"
                    >
                        {journalList.map((item, idx) => {
                            const atype = item.atype;
                            let showHtml = '';
                            if (atype === 1) {
                                showHtml =
                                    <video
                                        src={item.filePath}
                                        controls="controls"
                                        style={{ width: 350, height: 200 }}
                                    />;
                            } else if (atype === 2) {
                                showHtml =
                                    <div
                                        style={{
                                            width: 350,
                                            height: 200,
                                            backgroundImage: `url("${item.filePath}")`,
                                            backgroundRepeat: 'no-repeat',
                                            backgroundPosition: 'center',
                                            backgroundSize: 'cover',
                                            border: '1px solid #d9d9d9',
                                            borderRadius: 6
                                        }}
                                    />;
                            } else if (atype === 3) {
                                showHtml =
                                    <Input.TextArea
                                        readOnly={true}
                                        value={item.filePath}
                                        style={{
                                            width: 350,
                                            height: 200,
                                            resize: 'none'
                                        }}
                                    />
                            }
                            return (
                                <Card id={'journalId_' + item.journalId} style={{display:'flex',justifyContent:'center'}}>
                                    <Row style={{width: 350}}>
                                        <Col span={24}>期刊名称：{item.aname}</Col>
                                        <Col span={12}>时间：{item.createTime}</Col>
                                        <Col span={12}>运营商：{(APP.isValidObj(item.companyName) ? item.companyName : '未知')}</Col>
                                        <Col span={12}>创建人：{item.creatorName}</Col>
                                        <Col span={12}>期刊状态：{item.isenabled}</Col>
                                        <Col span={12}>点位上传状态：{item.xstatus}</Col>
                                        <Col span={12}>期刊类型：{item.journalTypeName}</Col>
                                    </Row>
                                    <Row>{showHtml}</Row>
                                </Card>
                            );
                        })}
                    </Drawer>
                </PageHeaderWrapper>
            </Spin>
        );
    }

    columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',
        },
        {
            title: '运营商',
            dataIndex: 'operatorName',
            key: 'operatorName',
        },
        {
            title: '楼盘名称',
            dataIndex: 'hourseName',
            key: 'hourseName',
        },
        {
            title: '楼盘类型',
            dataIndex: 'gvlistName',
            key: 'gvlistName',
        },
        {
            title: '区域',
            dataIndex: 'areaName',
            key: 'areaName',
        },
        {
            title: '点位名称',
            dataIndex: 'elevatorName',
            key: 'elevatorName'
        },
        {
            title: '设备生产商',
            dataIndex: 'producer',
            key: 'producer'
        },
        {
            title: '机器串码',
            dataIndex: 'imei',
            key: 'imei'
        },
        {
            title: '上架状态',
            dataIndex: 'isenabled',
            key: 'isenabled'
        },
        {
            title: '设备状态',
            dataIndex: 'xstatus',
            key: 'xstatus',
            render: (text) => {
                if(text.indexOf('离线') > -1) {
                    text = <span style={{color:'red'}}>{text}</span>;
                }
                return text;
            }
        },
        {
            title: '期刊数量',
            dataIndex: 'journalCount',
            key: 'journalCount',
            render: (text, record) => {
                let html = text + "（上架数：" + record.enaJournalCount + "）";
                if (text > 0) {
                    html = <a onClick={() =>{this.showJournal(record.id)}}>{html}</a>;
                }
                return html;
            }
        },
        {
            title: '安装日期',
            dataIndex: 'installDate',
            key: 'installDate',
            render: (text) => {
                if(text) return APP.momentFormatToStr(moment(text, 'YYYY-MM-DD'));
                return  "";
            }
        },
        {
            title: '安装人',
            dataIndex: 'employeeName',
            key: 'employeeName'
        },
        {
            title: '备注',
            dataIndex: 'remark',
            key: 'remark'
        },
        {
            title: '操作',
            render: (text, record) => {
                return <a onClick={() =>{this.showDeviceLog(record.id)}}>查看日志</a>;
            }
        }
    ];

    showJournal(pointId){
        const that = this, { dispatch } = this.props;
        APP.loading(that);
        dispatch({
            type: "pointModel/showJournalListByPointId",
            payload: {
                pointId: pointId
            },
            callback: function(data){
                APP.closeLoading(that);
                if(data.success){
                    that.setState({
                        journalList:data.datas,
                        isShowJournalListDrawer: true,
                    });
                }else{
                    message.error("操作失败！");
                }
            }
        });
    }

    showDeviceLog(pointId) {
        router.push({
            pathname: '/deviceLog/showDeviceLog',
            state: {pointId: pointId}
        });
    }
}

export default point;
